/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { forwardRef, useCallback, useState, useEffect } from "react";
import { Cascader } from "antd";
import { connect } from "dva";
import propTypes from "prop-types";
import { isLegalData } from "@/utils/utils";
import { flatMapDeep, isEmpty, unionBy } from "lodash";

const labelStyle = {
  overflow: "hidden",
  whiteSpace: "nowrap",
  textOverflow: "ellipsis",
};

/**
 * 将branch数组转换成对应的树结构数据
 */
const arrToTree = (data, canChooseParent, currentUserLevel) => {
  const result = [];
  if (!Array.isArray(data)) {
    return result;
  }
  data.forEach(item => {
    delete item.children;
  });
  const map = {};
  data.forEach(item => {
    map[item.id] = item;
  });
  data.forEach(item => {
    const parent = map[item.pid];
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
      if (!canChooseParent) {
        //  当前层级父节节点不可选择
        currentUserLevel >= item.level && (parent.disabled = true);
      } else {
        parent.disabled = false;
      }
    } else {
      result.push(item);
    }
  });
  return result;
};
const levelArr = ["总公司", "省", "市", "区/县", "支局"];
const yzLevelArr = ["总公司", "省", "市", "区/县", "街道数据"];
const AddressCascader = React.memo(
  forwardRef((props, ref) => {
    const {
      value,
      onChange,
      dispatch,
      type,
      zySelectedArray,
      branch = [],
      companyId,
      width,
      user_info,
      request = false,
      onSelect,
      optionsFromProps = [],
      level = 4,
      canChooseParent = true,
      ...restProps
    } = props;
    const [options, setOptions] = useState([]);
    const [area, setArea] = useState("");

    useEffect(
      () => {
        // 账号管理添加支局（非总公司）
        if (!request && branch.length > 0) {
          setOptions(arrToTree(branch, canChooseParent));
        }
        // 中邮总公司账号添加支局时，驿站搜索，共配县级区域，需要从user_info的branchId去获取下拉地址
        if (request && !!companyId && branch.length == 0) {
          const payload = {
            type: "cascader",
            id: companyId,
            take_self: 1,
          };
          if (type == "cache") {
            // 共配县级区域，删除take_self字段
            delete payload.take_self;
          }
          dispatch({
            type: "accounts/zyGetCompaniesList",
            payload,
          }).then(res => {
            const areaArr = isLegalData(res.data, []);
            if (type == "search") {
              areaArr.map(val => {
                if (val.name == "全部地区") {
                  val.isLeaf = true;
                }
              });
            }
            if (type == "cache" && value.length !== 0) {
              // 判断初始的value值
              setOptions(optionsFromProps, canChooseParent);
            } else {
              setOptions(areaArr);
            }
          });
        }
      },
      [companyId, type]
    );

    useEffect(
      () => {
        const currentUserLevel = user_info.branchLevel;
        const isZyAccount = user_info.user_type == "2" || user_info.user_type == "3";
        // 是否是下属驿站或待审核驿站页面(需要过滤)
        const isAreaList = type == "under_modify" || type == "audit" || type == "postDetail";
        // 是否是中邮总公司账号
        const isTopAccount = currentUserLevel == 0;
        // 中邮总公司账号、快宝驿站账号不需要过滤
        const shouldNotFilter = isZyAccount ? (isTopAccount ? !isAreaList : false) : true;
        // 设置从编辑带过来的所属区域数据，达到显示默认值的效果
        if (request && branch.length > 0 && optionsFromProps.length == 0) {
          // 当前账号是区县一级时，不需要请求区县一级的数据
          const requestAll = (type == "cache" || type == "zj") && currentUserLevel == "3" ? 0 : 1;
          const noRequsetBranch = shouldNotFilter
            ? branch
            : branch.filter(val => val.level <= currentUserLevel && val.level != 0);
          // 需要轮询的层级数据
          const requestBranch = shouldNotFilter
            ? branch
            : branch.filter(val => val.level > currentUserLevel - requestAll);
          // 过滤支局轮询请求
          value.length > 0 &&
            options.length == 0 &&
            Promise.all([
              ...requestBranch.filter(i => i.level != 4).map(val =>
                dispatch({
                  type: isZyAccount ? "accounts/zyGetCompaniesList" : "global/kbGetArearList",
                  payload: isZyAccount
                    ? {
                        type: "cascader",
                        id: val.id,
                      }
                    : {
                        code: val.code,
                      },
                })
                  .then(res => {
                    const arr = [...isLegalData(res.data, [])];
                    arr.map(val => {
                      Number(val.level) >= Number(level) && (val.isLeaf = true);
                    });
                    return arr;
                  })
                  .catch(err => {
                    console.log("err:", err);
                  })
              ),
            ])
              .then((res = []) => {
                // 防止修改原数据
                // concat是为了显示默认值
                const newArr = unionBy([...flatMapDeep(res).concat(noRequsetBranch)], "id").filter(
                  i => i
                );
                setOptions(arrToTree(newArr, canChooseParent, currentUserLevel));
              })
              .catch(err => {
                console.log("err", err);
              });
        } else if (branch.length > 0) {
          setOptions(optionsFromProps, canChooseParent);
        }
      },
      [type, value, user_info]
    );

    useEffect(
      () => {
        if (type == "add") {
          // 添加账号时，设置所属区域显示的文字
          const { length } = zySelectedArray;
          const stringArea = zySelectedArray.map(val => val.name).join(" ");
          const lastId = zySelectedArray.slice(length - 1, length)[0].id;
          setArea(stringArea);
          triggerChange(lastId);
        }
      },
      [zySelectedArray, type, triggerChange]
    );

    const handleChange = (value, selectedOptions) => {
      triggerChange(value);
      onSelect && onSelect(value, selectedOptions, options);
    };

    const triggerChange = useCallback(
      changedValue => {
        onChange && onChange(changedValue);
      },
      [onChange]
    );

    const handleLoadData = selectedOptions => {
      // 驿加易、中邮调用相同的api
      const isZyAccount = user_info.user_type == "2" || user_info.user_type == "3";
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      // 异步加载级联所需的数据
      dispatch({
        type: isZyAccount ? "accounts/zyGetCompaniesList" : "global/kbGetArearList",
        payload: isZyAccount
          ? {
              type: "cascader",
              id: targetOption.id,
            }
          : {
              code: targetOption.code,
            },
      }).then(res => {
        const { data } = res;
        const areaArr = isLegalData(data, []);
        if (data[0] && data[0].level == level) {
          // 当账号管理，添加支局时，不能显示最后的支局
          data.map(val => (val.isLeaf = true));
        }
        if (type == "search") {
          areaArr.map(val => {
            val.name == "全部地区" && (val.isLeaf = true);
          });
        }
        const arr = isZyAccount ? levelArr : yzLevelArr;
        if (isEmpty(data)) {
          targetOption.children = [
            {
              name: `暂无${arr[Number(targetOption.level) + 1]}`,
              disabled: true,
              isLeaf: true,
              id: "-1",
              code: "-1",
            },
          ];
        } else {
          targetOption.children = areaArr;
        }
        targetOption.loading = false;
        setOptions([...options]);
      });
    };

    const displayRender = label => {
      return (
        <div title={`${label.join(" / ")}`} style={labelStyle}>
          {label.join(" / ")}
        </div>
      );
    };

    return (
      <>
        {type == "add" ? (
          <span>{area}</span>
        ) : (
          <Cascader
            style={{ width }}
            allowClear={type == "search"}
            value={value}
            fieldNames={{ label: "name", value: "id" }}
            ref={ref}
            options={options}
            changeOnSelect={type == "modify" || type == "search"}
            onChange={handleChange}
            loadData={handleLoadData}
            notFoundContent="暂无数据"
            displayRender={displayRender}
            {...restProps}
          />
        )}
      </>
    );
  })
);

AddressCascader.propTypes = {
  type: propTypes.string.isRequired, //  zj(支局)，modify(编辑)，add(添加账号)，audit(待审核驿站)，search(驿站搜索)，under_modify(下属驿站修改支局)，cache(共配县级区域选择)
  branch: propTypes.array.isRequired, //  点击编辑时，传入的默认地址
  companyId: propTypes.string.isRequired, //  点击编辑时，传入当前账号所属地区的id，用于初始拉取地区列表
  optionsFromProps: propTypes.array, //  从外部传入的缓存options，当传入时，组件则不会去遍历请求下拉数据
  request: propTypes.bool, //  是否轮询接口拼接数据
  level: propTypes.number, //  展示到多少层级，0:中邮总局，1:省，2:市，3:区/县，4:中邮支局
  canChooseParent: propTypes.bool, //  父级是否可选择
};

AddressCascader.defaultProps = {
  request: true,
  level: 4,
  canChooseParent: true,
  optionsFromProps: [],
};

export default connect(
  ({ accounts, user }) => ({
    user_info: user.currentUser.user_info,
    zySelectedArray: accounts.zySelectedArray,
  }),
  null,
  null,
  { forwardRef: true }
)(AddressCascader);
